package com.heba;

import android.app.Activity;
import android.content.Context;

import java.util.Stack;

/**
 *
 * <p>
 * Created by shenghao on 2015/5/18.
 */
public class AppManager {

    private static Stack<Activity> activityStack;
    private static AppManager instance;

    private AppManager() {
    }

    /**
     *
     */
    public static AppManager getAppManager() {
        if (instance == null) {

            synchronized (AppManager.class) {
                if (instance == null) {
                    instance = new AppManager();
                }
            }

        }
        return instance;
    }

    /**
     *
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<>();
        }
        activityStack.add(activity);
    }

    /**
     *
     */
    public Activity currentActivity() {
        Activity activity = activityStack.lastElement();
        return activity;
    }

    /**
     *
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     *
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
        }
    }

    /**
     *
     *
     *
     * @param activity
     */
    public void removeActivityFromStack(Activity activity) {
        if (activity != null && activityStack.contains(activity)) {
            activityStack.remove(activity);
        }
    }

    /**
     *
     */
    public void finishActivity(Class<?> cls) {
        for (int i = 0; i < activityStack.size(); i++) {
            Activity activity = activityStack.get(i);
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     *
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    /**
     *
     */
    public void toMainActivity() {
        for (Activity activity : activityStack) {
            if (!(activity == activityStack.firstElement())) {
                activity.finish();
            }
        }
    }

}
